package com.zking.forward.index;

import com.zking.dao.UserDao;
import com.zking.entity.User;
import com.zking.util.RedirectMsg;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class Login extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理请求的编码，解决中文乱码
        request.setCharacterEncoding("utf-8");
        //处理响应的编码 ，解决中文乱码
        response.setContentType("text/html;charset=utf-8");

        System.out.println("Login===进来");
        //能进入到登录的Login说明验证码没有问题的，只需要用户名和密码进行比对
        String name = request.getParameter("userName");
        String password = request.getParameter("password");

        User user = UserDao.getUser(name, password);
        if(user != null){//用户名和密码是正确的
            //登录成功之后 显示商品的首页--重定向商品分页查询的servlet
            //同时需要把登录的用户信息存到session
            request.getSession().setAttribute("user", user);
            response.sendRedirect("productSelectByPage");
            return;
        }else{
            request.setAttribute("msg", RedirectMsg.loginError);
            request.setAttribute("pageName", RedirectMsg.loginPageName);
            request.setAttribute("url", RedirectMsg.loginUrl);
            request.getRequestDispatcher("redirect.jsp").forward(request, response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
